package com.df.common.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.df.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * controller层统一异常处理
 * @author yangjd
 * @date 2021-10-28
 */

@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandler {

    // token鉴权异常
    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<?> authExceptionHandler(NotLoginException e) {
        Map<String,Object> map = new HashMap<>();
        map.put("message", "登录失效，请重新登录！");
        map.put("timestamp", new Date());
        return new ResponseEntity<>(map, HttpStatus.UNAUTHORIZED);
    }

    // 业务逻辑异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<?> logicExceptionHandler(BusinessException e) {
        Map<String,Object> map = new HashMap<>();
        map.put("message", e.getMessage());
        map.put("timestamp", new Date());
        return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
    }

    // 权限异常
    @ExceptionHandler(NotPermissionException.class)
    public ResponseEntity<?> notPermissionExceptionHandler(NotPermissionException e) {
        Map<String,Object> map = new HashMap<>();
        map.put("message", "无此权限");
        map.put("timestamp", new Date());
        return new ResponseEntity<>(map, HttpStatus.FORBIDDEN);
    }

    // 其他异常处理
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> exceptionHandler(Exception e) {
        Map<String,Object> map = new HashMap<>();
        map.put("message", e.getMessage());
        map.put("timestamp", new Date());
        e.printStackTrace();
        return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
    }
}